package com.earthea.scaffold.common.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.earthea.common.io.excel.ExcelUtils;
import com.earthea.scaffold.common.enums.SelectEnum;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.UUID;

/**
 * Excel相关处理
 */
@Slf4j
public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param response  响应体
     * @param sheetName sheet名称
     * @param dataList  数据
     * @param clazz     数据类型
     */
    public static <T> void export(HttpServletResponse response, String sheetName, Collection<T> dataList, Class<T> clazz) {
        String fileName = UUID.randomUUID() + "_" + sheetName + ".xlsx";
        ExcelUtils.write(fileName, sheetName, dataList, clazz);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            IOUtils.copy(inputStream, response.getOutputStream());
        } catch (IOException e) {
            log.error("导出文件失败", e);
        }
        FileUtils.deleteQuietly(new File(fileName));
    }

    public static class SelectEnumConverter implements Converter<SelectEnum<?>> {

        @Override
        public Class<String> supportJavaTypeKey() {
            return String.class;
        }

        @Override
        public CellDataTypeEnum supportExcelTypeKey() {
            return CellDataTypeEnum.STRING;
        }

        @Override
        public WriteCellData<String> convertToExcelData(SelectEnum value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
            return new WriteCellData<>(value.getLabel());
        }
    }
}
